﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebSocketClientApp
{
    public partial class Form3 : Form
    {
        private WebSocketClient3 _client;

        public findDeviceWaitForm _findDeviceWaitForm;

        public ConnectDeviceWaitForm _connectDeviceWaitForm;
        /// <summary>
        /// 服务端回复的设备的列表
        /// </summary>
        public List<SendFindReplyDevicesubClass> m_device_list = new List<SendFindReplyDevicesubClass>();
        public Form3()
        {
            InitializeComponent();
            this._client = new WebSocketClient3();
            this._client.DeviceFindReplyChanged += client_DeviceFindReplyChanged;
            lsb_device_list.DisplayMember = "name";
        }
        /// <summary>
        /// 收到服务端回复搜索设备的数据
        /// </summary>
        /// <param name="msg"></param>
        private void client_DeviceFindReplyChanged(string msg)
        {
            try
            {
                RunAsync(() => {
                    SendFindReplyDeviceClass my_sendFindReDeviceClass = JsonConvert.DeserializeObject<SendFindReplyDeviceClass>(msg);
                    if (my_sendFindReDeviceClass != null)
                    {
                        if (my_sendFindReDeviceClass.command == CommondCode.find_device_reply.ToString())
                        {
                            if (_findDeviceWaitForm != null) 
                            {
                                _findDeviceWaitForm.DialogResult = DialogResult.OK;
                            }
                            //收到的搜索设备的回复
                            SendFindReplyDevicesubClass my_device = my_sendFindReDeviceClass.device;
                            m_device_list.Add(my_device);
                            lsb_device_list.SafeInvoke(() => lsb_device_list.Items.Add(my_device));
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        // 异步线程
        public static void RunAsync(Action action)
        {
            try
            {
                ((Action)(delegate ()
                {
                    action.Invoke();
                })).BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 连接webSocket服务端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_connecnt_server_Click(object sender, EventArgs e)
        {
            try
            {
                await _client.ConnectAsync();
                using (var popup = new PopupForm("WebSocket 客户端已连接！", 2000))
                {
                    popup.StartPosition = FormStartPosition.CenterScreen;
                    popup.ShowDialog(); // 或者使用 Show() 方法，取决于是否需要模态窗口
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                MessageBox.Show($"连接失败1：{ex.Message}");
            }
        }
        /// <summary>
        /// 功能：搜索设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_seacher_device_Click(object sender, EventArgs e)
        {
            try
            {
                m_device_list.Clear();
                SendFindDeviceClass my_sendFindDeviceClass = new SendFindDeviceClass();
                my_sendFindDeviceClass.command = CommondCode.find_device.ToString();
                string my_send_data = JsonConvert.SerializeObject(my_sendFindDeviceClass);
                if (_client.getClientStats())
                {
                    //已经连接服务器
                    try
                    {
                        await _client.SendMessageAsync(my_send_data);

                        _findDeviceWaitForm = new findDeviceWaitForm();
                        _findDeviceWaitForm.ShowDialog();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"发送失败：{ex.Message}");
                    }
                }
                else 
                {
                    //未连接到服务器，给出提示
                    using (var popup = new PopupForm("WebSocket 客户端未连接！", 2000))
                    {
                        popup.StartPosition = FormStartPosition.CenterScreen;
                        popup.ShowDialog(); // 或者使用 Show() 方法，取决于是否需要模态窗口
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }

        private void timer_find_device_Tick(object sender, EventArgs e)
        {
            try
            {
                if (InfoClass.isFindeDevice == true) 
                {
                    _findDeviceWaitForm.DialogResult = DialogResult.OK;

                    // 将收到的数据展示
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：连接（客户端发连接设备）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_connect_device_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lsb_device_list.SelectedItem != null) 
                {
                    SendFindReplyDevicesubClass my_device = (SendFindReplyDevicesubClass)this.lsb_device_list.SelectedItem;

                    SendConnectDeviceSubClass my_sendConnectDeviceSubClass = new SendConnectDeviceSubClass();
                    my_sendConnectDeviceSubClass.name = my_device.name;
                    my_sendConnectDeviceSubClass.mac = my_device.mac;
                    SendConnectDeviceClass my_sendConnectDeviceClass = new SendConnectDeviceClass();
                    my_sendConnectDeviceClass.command = CommondCode.connect_device.ToString();
                    my_sendConnectDeviceClass.sendConnectDeviceSubClass = my_sendConnectDeviceSubClass;
                    string my_send_data = JsonConvert.SerializeObject(my_sendConnectDeviceClass);
                    if (_client.getClientStats())
                    {
                        //已经连接服务器
                        try
                        {
                            await _client.SendMessageAsync(my_send_data);

                            _connectDeviceWaitForm = new ConnectDeviceWaitForm();
                            _connectDeviceWaitForm.ShowDialog();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"发送失败：{ex.Message}");
                        }
                    }
                    else
                    {
                        //未连接到服务器，给出提示
                        using (var popup = new PopupForm("WebSocket 客户端未连接！", 2000))
                        {
                            popup.StartPosition = FormStartPosition.CenterScreen;
                            popup.ShowDialog(); // 或者使用 Show() 方法，取决于是否需要模态窗口
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
    }
}
